<?php

namespace common\model;

use think\Hook;
use think\model\RelationModel;
use think\module\Module;
use teamones\dbeventObserver\SplSubjectEnforcer;
use teamones\dbeventObserver\interfaces\SplSubject;

class TaskModel extends RelationModel implements SplSubject
{
    use SplSubjectEnforcer;

    // 任务处理状态 所有已提交状态范围
    const DEAL_STATUS_SUBMITTED_SCOPE = [
        'submitted', 'pending', 'processing', 'processed',
    ];

    const STEP_TYPE_STEP = 'step'; // 工序任务
    const STEP_TYPE_STEP_CATEGORY = 'step_category'; // 工序分类任务
    const STEP_TYPE_TO_DO = 'to_do'; // 个人待办任务
    const STEP_TYPE_PERSON = 'person'; // 个人待办任务
    const STEP_TYPE_WORK_ORDER_TO_DO = 'work_order_to_do'; // 工单待办
    const STEP_TYPE_ENTITY_TO_DO = 'entity_to_do'; // 实体待办
    const STEP_TYPE_STANDARD_MEETING = 'standard_meeting'; // 标准会议
    const STEP_TYPE_STANDARD_REVIEW = 'standard_review'; // 标准审核
    const STEP_TYPE_STANDARD_MAKE_TO_DO = 'standard_make_to_do'; // 标准制作

    const STEP_TYPE_TEMPLATE_TO_DO = 'template_to_do'; // 模板代办主任务

    const STEP_TYPE_TODO_GROUP = [
        self::STEP_TYPE_TO_DO,
        self::STEP_TYPE_WORK_ORDER_TO_DO,
        self::STEP_TYPE_ENTITY_TO_DO,
        self::STEP_TYPE_STANDARD_MEETING,
        self::STEP_TYPE_STANDARD_MAKE_TO_DO,
        self::STEP_TYPE_STANDARD_REVIEW,
    ];

    // 任务执行者类型
    const EXECUTOR_TYPE_INSIDE = 'inside'; // 内部
    const EXECUTOR_TYPE_OUTSIDE = 'outside'; //  外部
    const EXECUTOR_TYPE_TENANT_GROUP = 'tenant_group'; // 集团
    const EXECUTOR_TYPE_DEFAULT = 'default'; // 默认状态

    // 任务被外包的标识类型
    const OUTSIDE_EXECUTE_TYPE_GROUP = [
        self::EXECUTOR_TYPE_TENANT_GROUP,
        self::EXECUTOR_TYPE_OUTSIDE,
    ];


    // 任务分配状态
    const ASSIGN_STATUS_DEFAULT = 'default'; // 默认状态 待制片分配
    const ASSIGN_STATUS_DEPARTMENT = 'department'; // 已分配到部门
    const ASSIGN_STATUS_EXECUTOR = 'executor'; // 已分配到组员
    const ASSIGN_STATUS_WAIT_CONFIRM = 'wait_confirm'; // 等待确认
    const ASSIGN_STATUS_REJECTED = 'rejected'; // 已拒绝

    //自动验证
    protected $_validate = [
        ['name', '1,128', '', self::EXISTS_VALIDATE, 'length'],
        ['code', '0,128', '', self::EXISTS_VALIDATE, 'length'],
//        ['code', '', '', self::EXISTS_VALIDATE, 'alphaDash'],
        ['type', ['normal', 'shadow', 'sub'], '', self::EXISTS_VALIDATE, 'in'], // 任务类型
        ['tenant_id', '', '', self::EXISTS_VALIDATE, 'integer'], // 租户id
        ['project_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['entity_module_id', '', '', self::EXISTS_VALIDATE, 'integer'],
//        ['step_id', '', '', self::EXISTS_VALIDATE, 'integer'],
        ['plan_start_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['plan_end_time', '', '', self::EXISTS_VALIDATE, 'date'],
        ['plan_duration', '0,8', '', self::EXISTS_VALIDATE, 'length'],
        ['plan_duration', '', '', self::EXISTS_VALIDATE, 'number'],
        ['json', '', '', self::EXISTS_VALIDATE, 'array'],
        ['deal_status', ['no_submit', 'to_submit', 'submitted', 'pending', 'processing', 'processed'], '', self::EXISTS_VALIDATE, 'in'],
    ];

    //自动完成
    protected $_auto = [
        ['tenant_id', 'auto_fill_tenant_id', self::MODEL_INSERT, 'function'],
        ['project_id', 'auto_fill_project_id', self::MODEL_INSERT, 'function_with_data'],
        ['code', 'auto_fill_code', self::MODEL_INSERT, 'function_with_data'],
        ['plan_start_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['plan_end_time', 'strtotime', self::EXISTS_VALIDATE, 'function'],
        ['json', 'json_encode', self::EXISTS_VALIDATE, 'function'],
        ['created_by', 'fill_created_by', self::MODEL_INSERT, 'function'],
        ['created', 'time', self::MODEL_INSERT, 'function'],
        ['uuid', 'create_uuid', self::MODEL_INSERT, 'function'],
        ['description', 'fill_text_default_val', self::MODEL_INSERT, 'function'],
        ['updated_by', 'fill_created_by', self::MODEL_UPDATE, 'function'],
        ['updated', 'time', self::MODEL_UPDATE, 'function'],
    ];

    // 隐藏字段
    protected $hidden = ['json'];

    /**
     * 获取器：自定义字段
     * @param $value
     * @param $data
     * @return array
     */
    public function getJsonAttr($value, $data)
    {
        $this->appendCustomField = [];
        // 当前模块的自定义字段配置
        $fieldDict = Module::$moduleDictData['field_index_by_code']['task']['custom'];

        // 判断是否有值
        if (!empty($value)) {
            $jsonDictData = json_decode($value, true);
        } else {
            $jsonDictData = [];
        }

        // 把自定义值写入追加字段
        foreach ($fieldDict as $field => $config) {
            if (array_key_exists($field, $jsonDictData)) {
                $this->appendCustomField[$field] = $jsonDictData[$field];
            } else {
                // 没有值赋空值
                $this->appendCustomField[$field] = "";
            }
        }

        return $this->appendCustomField;
    }

    /**
     * @param $data
     * @param $options
     * @return void
     */
    public function _before_insert(&$data, $options)
    {
        parent::_before_insert($data, $options); // TODO: Change the autogenerated stub
        $data['step_id'] = intval($data['step_id'] ?? 0);
    }

    /**
     * @param $result
     * @param $pkName
     * @param $data
     * @param $options
     * @param $writeEvent
     * @return void
     */
    public function _after_update($result, $pkName, $data, $options, $writeEvent)
    {
        parent::_after_update($result, $pkName, $data, $options, $writeEvent); // TODO: Change the autogenerated stub
        if (!empty($options['disable_db_after']) && $options['disable_db_after'] === true) {
            // 禁用db后处理事件
            return;
        }

        Hook::listen('task_reference_asset_update_after', $data);//同步甲乙双reference_asset资产数据
        Hook::listen('task_status_update_after', $data);
    }

    /**
     * 获取器：计划开始时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getPlanStartTimeAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }


    /**
     * 获取器：计划结束时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getPlanEndTimeAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }

    /**
     * 获取器：创建时间
     * @param $value
     * @param $data
     * @return array|mixed
     */
//    public function getCreatedAttr($value, $data)
//    {
//        if (!empty($value)) {
//            return get_format_date($value, 1);
//        }
//        return "";
//    }
}
